package com.gnerv.battle.boot.module.base.service.impl;

import com.gnerv.battle.boot.common.base.exception.BusinessException;
import com.gnerv.battle.boot.common.tools.GsonTools;
import com.gnerv.battle.boot.module.base.model.entity.RoleDataPermission;
import com.gnerv.battle.boot.module.base.repository.mapper.TenantMapper;
import com.gnerv.battle.boot.module.base.service.CurrentAccountService;
import com.gnerv.battle.boot.module.base.service.TenantService;
import com.google.common.collect.Sets;
import com.google.gson.reflect.TypeToken;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Set;

@Slf4j
@Service
@AllArgsConstructor
public class TenantServiceImpl implements TenantService {

    private final CurrentAccountService currentAccountService;
    private final TenantMapper tenantMapper;

    @Override
    public Set<String> listAccountUkIdByRoleAndOrg() {
        Set<String> roleUkIdSet = Sets.newHashSet();
        Set<String> orgUkIdSet = Sets.newHashSet();
        String username = currentAccountService.username();
        if ("admin".equals(username)) {
            return tenantMapper.listAccountUkId();
        }
        Set<String> currentAccountRoleUkIdSet = tenantMapper.listRoleUkIdByAccountUkId(currentAccountService.accountUkId());
        List<RoleDataPermission> roleDataPermissions = tenantMapper.listByRoleUkIdSet(currentAccountRoleUkIdSet);
        for (RoleDataPermission roleDataPermission : roleDataPermissions) {
            String role = roleDataPermission.getRole();
            roleUkIdSet.add(GsonTools.GSON.fromJson(role, new TypeToken<List<String>>() {
            }.getType()));
            String org = roleDataPermission.getRole();
            orgUkIdSet.add(GsonTools.GSON.fromJson(org, new TypeToken<List<String>>() {
            }.getType()));
        }
        Set<String> accountUkIdSet = tenantMapper.listAccountUkIdByRoleUkIdSetAndOrgUkIdSet(roleUkIdSet, orgUkIdSet);
        if (CollectionUtils.isEmpty(accountUkIdSet)) {
            throw new BusinessException("permission error");
        }
        return accountUkIdSet;
    }

}